package com.dl.base.utils

import android.content.Context
import android.hardware.Camera
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.os.Build
import com.dl.base.extendsion.isNotNull
import kotlinx.coroutines.delay

object CameraUtil {
    private suspend fun flash(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                //获取CameraManager
                val mCameraManager =
                    context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
                //获取当前手机所有摄像头设备ID
                val ids = mCameraManager.cameraIdList
                var cameraId = ""
                for (id in ids) {
                    val c = mCameraManager.getCameraCharacteristics(id)
                    //查询该摄像头组件是否包含闪光灯
                    val flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)
                    val lensFacing = c.get(CameraCharacteristics.LENS_FACING)
                    if (flashAvailable != null && flashAvailable
                        && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK
                    ) {
                        cameraId = id
                    }
                }
                if (cameraId.isNotNull()) {
                    repeat(4) {
                        mCameraManager.setTorchMode(cameraId, true)
                        delay(150)
                        mCameraManager.setTorchMode(cameraId, false)
                    }
                }
            } catch (e: CameraAccessException) {
                e.printStackTrace()
            }
        } else {
            val camera = Camera.open()
            try {
                repeat(4) {
                    camera.startPreview()
                    var parameters: Camera.Parameters = camera.parameters
                    parameters.flashMode = Camera.Parameters.FLASH_MODE_TORCH
                    camera.parameters = parameters
                    delay(150)
                    parameters = camera.parameters
                    parameters.flashMode = Camera.Parameters.FLASH_MODE_OFF
                    camera.parameters = parameters
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                camera.release()
            }
        }
    }
}